#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import os
import urllib
from sklearn.decomposition import PCA


def downLoadIris():
    """下载数据文件"""
    dataFile = 'iris.data'
    if not os.path.isfile(dataFile):
        urllib.request.urlretrieve(
            'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data',
            dataFile)

    # 使用 numpy.loadtxt 载入数据
    # iris.data 的最后一列是 bytes 类型， 用 converters 参数将其转化为浮点型
    data = np.loadtxt(
        dataFile,
        delimiter=',',
        converters={
            4:
            lambda b: [b'Iris-setosa', b'Iris-versicolor', b'Iris-virginica'].index(b)
        })

    # 保存 150 x 5 数据
    np.savetxt('iris-150x5.data', data)

    # 保存4特征训练数据
    d120 = np.vstack([data[0:40], data[50:90], data[100:140]])
    ft = open('iris-4-train.data', 'w')
    ft.writelines('120 4 3' + os.linesep)

    for row in d120:
        index = np.array([0, 0, 0])
        ft.writelines('%2.2f %2.2f %2.2f %2.2f' % tuple(row[:-1]) + os.linesep)
        c = int(row[-1])
        index[c] = 1
        ft.writelines(np.array2string(index)[1:-1] + os.linesep)
    ft.close()

    # 保存4特征测试数据
    d30x = np.vstack([data[40:50, :-1], data[90:100, :-1], data[140:150, :-1]])
    d30y = np.vstack([data[40:50, -1:], data[90:100, -1:], data[140:150, -1:]])
    np.savetxt('iris-4-test-x.data', d30x, fmt='%2.2f', delimiter=',')
    np.savetxt('iris-4-test-y.data', d30y, fmt='%d', delimiter=',')

    # 保存4特征数据
    X4 = data[:, :-1]
    Y = data[:, -1:]
    np.savetxt('iris-4.data', X4, fmt='%10.6f', delimiter=',')
    np.savetxt('iris-y.data', Y, fmt='%d', delimiter=',')

    # 保存2特征数据
    r = np.random.RandomState()
    pca = PCA(n_components=2, random_state=r, tol=1e-6)
    pca.fit(X4)
    X2 = pca.transform(X4)
    np.savetxt('iris-2.data', X2, fmt='%10.6f', delimiter=",")


downLoadIris()
